﻿package com.foxhis.webstart.download;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.CountDownLatch;


/**
 * 下载类
 * 
 * @author nestor
 * 
 * 2009-7-22 上午11:46:52
 */
public class Download implements Runnable  {


	final static private int MAX_BUFFER_SIZE = 2048;

	final static private int DOWNLOADING = 0;

	final static private int PAUSED = 1;

	final static private int COMPLETE = 2;

	final static private int CANCELLED = 3;

	final static private int ERROR = 4;

	private URL url;
	
	private String urlstr;

	private int size;

	private long downloaded;

	private int contentLength=0;

	private int status;

	private DownloadListen listen;

	private String downloadName;
	/*--------------------B (Darke 2012.03.02)--------------------*/
	private String version="";
	private int num;
	private CountDownLatch latch;
	private long startposition;
	private long endposition;
	private long locallenth;
	private BufferedOutputStream outf;
	private int counterror=0;
	public boolean beclose=false;
	private boolean isLAN=false;
	private File smbfile;
	private int waitfor=-1;
	/*--------------------E (Darke 2012.03.02)--------------------*/
	/**
	 * @param url
	 */
	public Download(String url) {
		this.size = -1;
		this.downloaded = 0;
		this.status = DOWNLOADING;
		try {
			this.url = new URL(url);
		} catch (MalformedURLException e) {
			listen.log(e.getMessage(),DownloadPanel.ERROR+"DownLoad Init URL--");
			throw new RuntimeException(e);
		}
	}
	
	public Download(String url,String version,DownloadListen listen,boolean isLAN) {
		this.listen=listen;
		this.version=version;
		this.isLAN=isLAN;
		this.size = -1;
		this.downloaded = 0;
		this.status = DOWNLOADING;
		try {
			initURL(url);
		} catch (MalformedURLException e) {
			listen.log(e.getMessage(),DownloadPanel.ERROR+"DownLoad Init URL--");
			throw new RuntimeException(e);
		}
	}

	public Download(URL url) {
		this.url = url;
		this.size = -1;
		this.downloaded = 0;
		this.status = DOWNLOADING;
	}
	
	public void initURL(String url) throws MalformedURLException{
		this.urlstr=url;
		if(isLAN){
			smbfile=new File(url);
			this.url=smbfile.toURL();
		}
		else{
			this.url = new URL(url);
		}

	}
	
	public boolean getLAN(){
		return isLAN;
	}

	/**
	 * 返回当前url地址
	 * 
	 * @return
	 */
	public String getUrl() {
		return urlstr;
	}

	/**
	 * 返回当前下载文件总长度
	 * 
	 * @return
	 */
	public int getSize() {
		return size;
	}

	/**
	 * 返回当前下载已完成长度
	 * 
	 * @return
	 */
	public long getLevel() {
		return downloaded;
	}

	/**
	 * 返回当前进度
	 * 
	 * @return
	 */
	public int getProgress() {
		return (int) ((double) downloaded / (double) size * 100);
	}

	public int getStatus() {
		return status;
	}

	public void pause() {
		status = PAUSED;
	}

	public void resume() {
		status = DOWNLOADING;
		download(listen);
	}

	public void cancel() {
		status = CANCELLED;
	}

	private void error() {
		status = ERROR;
	}
	
	public void setLAN(boolean value){
		isLAN=value;
	}

	public int getContentLength() {
		if(contentLength==0){
			this.contentLength=getAllContentLenth();
		}
		return contentLength;
	}

	public void download(DownloadListen listen) {
		this.listen = listen;
		System.out.println(status);
		// resume();
		Thread thread = new Thread(this);
		thread.start();
	}

	private String getFileName(URL url) {
		String fileName = url.getFile();
		fileName=fileName.substring(fileName.lastIndexOf('/') + 1);
		return fileName;
	}

	public String getFileName() {
		return getFileName(url);
	}

	public boolean isExists() {
		return new File(getFileName()).exists();
	}

	public String getDownloadName() {
		return downloadName;
	}

	public void setDownloadName(String downloadName) {
		this.downloadName = downloadName + "载入";
	}
	/*--------------------B (Darke 2012.03.02)--------------------*/
	public String getVersion(){
		return version;
	}
	
	public void initFile() throws Exception{
		String name=getFileName(url);
		String url_ =listen.getFileUrl(name)+"_"+version;
		File mainfile=new File(url_);
		/*if(!mainfile.exists()){
			mainfile.getParentFile().mkdirs();
		}*/
		this.locallenth=mainfile.length();
		this.outf=new BufferedOutputStream(new FileOutputStream(mainfile,true));
		//mainfile.seek(locallenth);
	}
	
	public void closeFile() throws IOException{
		this.outf.flush();
		this.outf.close();
		String name=getFileName(url);
		String url_ =listen.getFileUrl(name)+"_"+version;
		File mainfile=new File(url_);
		mainfile.delete();
	}
	
	private int getproce(long downded){
		int result=(int)(((double) (downded) / (double) contentLength) * 50);//+(mode==0?0:50);
		return (result>100)?100:result;
	}
	private int getAllContentLenth(){
		try {
			if(isLAN){
				contentLength=(int) smbfile.length();
				return contentLength;
			}
			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setRequestProperty("Range", "bytes=" + downloaded + "-");
			connection.connect();
			if (connection.getResponseCode() / 100 != 2) {
				error();
			}
			contentLength=connection.getContentLength();
		} catch (IOException e) {
			listen.log(e.getMessage(),DownloadPanel.ERROR+"getAllContentLenth--");
			e.printStackTrace();
		}
		return contentLength;
	}
	
	public void setMutiple(int num,CountDownLatch latch,long startposition,long endposition,long treadlenth){
		this.num=num;
		this.latch=latch;
		this.startposition=startposition;
		this.endposition=endposition;
	}
	/**
	 * 设置并获取断点
	 */
	public long[] setBreakPoint(long[] startpos,int treadNum,long threadlen){
		String name=getFileName(url);
		String url_ =listen.getFileUrl(name);
		long proce=0;
		DownloadPanel downpanel = (DownloadPanel) listen;
		for(int i=0;i<treadNum;i++){
			File temfile=new File(url_+"_"+version+"_"+i);
			startpos[i]=(i<(locallenth/threadlen))?contentLength:temfile.length();
			if(locallenth==0){
				proce+=startpos[i];
			}
		}
		proce=(locallenth==0)?proce:locallenth;
		listen.setCountValue(proce);
		int result=(int) (((double) (proce) / (double) contentLength) * 50)+((locallenth==0)?0:50);
		String mes = (getDownloadName() + "-已完成进度 " + result + " %").intern();
		downpanel.progressBar.setString(mes);
		downpanel.progressBar.setValue(result);
		return startpos;
	}
	
	public void copyfile(String copyfile,String todirectory){
		String cmdstr="cmd /c call copy /Y \""+copyfile+"\" \""+todirectory+"\"";
		System.out.println(cmdstr);
		try {
			Process pp=Runtime.getRuntime().exec(cmdstr);
			InputStream in=pp.getInputStream() ;
			InputStream err=pp.getErrorStream();
			OutputStream out=pp.getOutputStream();
//			listen.updateScreen((contentLength));
			new Thread() {
				@Override
				public void run() {
					long proce=0;
					int maxlen=3*contentLength/50;
					while(waitfor!=0){
						listen.updateScreen(30*(proce++));
						if(proce==maxlen){
							break;
						}
						try {
							sleep(3);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}.start();
			waitfor=pp.waitFor();
			listen.updateScreen(2*contentLength);
			in.close();
			err.close();
			out.flush();
			out.close();
//			listen.updateScreen(2*(contentLength));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		

	}
	/**
	 * 合并下载文件
	 */
	public boolean setTargetFile(int treadnum,long threadlen){
		String name=getFileName(url);
		String url_ =listen.getFileUrl(name);
		if(isLAN){
			try {
				closeFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return true;
		}
		downloaded=locallenth;
		boolean issussec=false;
		
	//	BufferedOutputStream outf=null;
		try{
			//outf=new BufferedOutputStream(new FileOutputStream(mainfile));
		for(int i=(int) (locallenth/threadlen);i<treadnum;i++){
			File tempf=new File(url_+"_"+version+"_"+i);
			if(tempf.exists()){
				BufferedInputStream intf=new BufferedInputStream(new FileInputStream(tempf));
				//RandomAccessFile intf=new RandomAccessFile(tempf, "rw");
				int len=0;
				byte[] b=new byte[MAX_BUFFER_SIZE];
				intf.skip(((i==(int) (locallenth/threadlen))&&(locallenth!=0))?((locallenth%threadlen)):0);
				//intf.seek(((i==(int) (locallenth/threadlen))&&(locallenth!=0))?((locallenth%threadlen)):0);
				while((len=intf.read(b))!=-1){
					downloaded+=len;
					outf.write(b, 0, len);
					b=new byte[MAX_BUFFER_SIZE];
					if(downloaded%5000==0){
						outf.flush();
					}
					listen.updateScreen(len);
				}
				intf.close();
				tempf.delete();
			}
		}
		outf.flush();
		outf.close();
		File temf=new File(url_+"_"+version);
		File mainf=new File(url_);
//		if(mainf.getName().equals(((DownloadPanel)listen).mainFile)){
//			listen.checkRun();
//		}
		if(!mainf.exists()){
			issussec=temf.renameTo(mainf);
			if(!issussec){
				System.out.println("文件无法覆盖！Error:001");
			}
		}
		else{
			if(mainf.delete()){
				issussec=temf.renameTo(mainf);
				if(!issussec){
					System.out.println("文件无法覆盖！Error:002");
				}
			}
			else{
				System.out.println("删除原文件失败！");
			}
		}
		}catch(Exception e){
			listen.log(e.getMessage(),DownloadPanel.ERROR+"setTargetFile--");
			e.printStackTrace();
		}finally{
			try {
				outf.flush();
				outf.close();
			} catch (IOException e1) {
				listen.log(e1.getMessage(),DownloadPanel.ERROR+"setTargetFile-Close outputstream-");
				e1.printStackTrace();
			}
		}
		return issussec;
		/*--------------------B (Darke)--------------------*/
		/*if(!(name.toLowerCase().endsWith(".jar")||name.toLowerCase().endsWith(".exe"))){
			listen.writeVersion(name);
		}*/
		//listen.updateScreen(1,downloaded);
		/*--------------------E (Darke)--------------------*/
	}
	/*--------------------E (Darke 2012.03.02)--------------------*/
	/**
	 * 进行文件下载并显示进度
	 */
	public void runr() {
		if (true) {
			/*--------------------B (Darke 2012.03.02)--------------------*/
			if(startposition>=endposition){
				latch.countDown();
				return;
			}
			/*--------------------E (Darke 2012.03.02)--------------------*/
			// System.out.println(url);
			//RandomAccessFile file = null;//Darke
			BufferedOutputStream outm=null;
			InputStream stream = null;
			try {
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				//connection.setRequestProperty("Range", "bytes=" + downloaded + "-");//Darke
				connection.setRequestProperty("Range", "bytes=" + startposition + "-"+endposition);//Darke
				connection.connect();
				if (connection.getResponseCode() / 100 != 2) {
					error();
				}
				//contentLength = connection.getContentLength();
				int tcontentLength = connection.getContentLength();
				//if (contentLength < 1) {//Darke
				if (tcontentLength < 1) {//Darke
					error();
				}
				if (size == -1) {
					//size = contentLength;//Darke
					size=tcontentLength;//Darke
				}
				downloaded=0;
				/*--------------------B (Darke 2012.01.31)--------------------*/
				//String url_ = getFileName(url).startsWith("Pastoral") ? getFileName(url) : "lib\\" + getFileName(url);
				String name=getFileName(url);
				try {
				stream = connection.getInputStream();
				}catch(Exception k){
					listen.log(k.getMessage(),DownloadPanel.ERROR);
					DownloadPanel downloadp=(DownloadPanel) listen;
					boolean ismain=name.equalsIgnoreCase(downloadp.mainFile);
					if(downloadp.errorMessage.isEmpty()){
						downloadp.errorMessage=((k instanceof java.io.FileNotFoundException)?
								"服务器无法找到"+(ismain?"运行文件":"文件")+"："+name:k.getMessage());
					}
					throw k;
				}

				String url_ =listen.getFileUrl(name)+"_"+version+"_"+num;
				System.out.println("DownUrl:"+url_);
				//file = new RandomAccessFile(DownloadPanel.u + url_, "rw");
				//file = new RandomAccessFile(url_, "rw");//Darke
				outm=new BufferedOutputStream(new FileOutputStream(url_, true));
				/*--------------------E (Darke 2012.01.31)--------------------*/
				//file.seek(file.length());//Darke
				////stream = connection.getInputStream();
				while (status == DOWNLOADING) {
					// System.out.println("Download...");
					byte buffer[];
					if (size - downloaded > MAX_BUFFER_SIZE) {
						buffer = new byte[MAX_BUFFER_SIZE];
					} else {
						buffer = new byte[(int) (size - downloaded)];
					}
					int read = stream.read(buffer);
					if (read == -1) {
						break;
					}
					outm.write(buffer, 0, read);//Darke
					downloaded += read;
					if(downloaded%5000==0){
						outm.flush();
					}
					listen.updateScreen(read);
					}
				try {
					/*--------------------B (Darke 2012.03.02)--------------------*/
					outm.flush();
					outm.close();
					outm = null;
					/*--------------------E (Darke 2012.03.02)--------------------*/
					stream.close();
					stream = null;
				} catch (Exception e) {
					listen.log(e.getMessage(),DownloadPanel.ERROR);
					e.printStackTrace();
				}

				// if (status == DOWNLOADING) {
				// status = COMPLETE;
				// System.out.println("call");
				// listen.call();
				// }
				// listen.runEXE();
				//listen.downFile();

			} catch (Exception e) {
				listen.log(e.getMessage(),DownloadPanel.ERROR);
				e.printStackTrace();
				//error();
			} finally {
				//listen.downFile();//Darke
				if (outm != null) {//Darke
					try {
						outm.flush();
						outm.close();
						outm = null;
					} catch (Exception e) {
						listen.log(e.getMessage(),DownloadPanel.ERROR);
					}
				}
				if (stream != null) {
					try {
						stream.close();
						stream = null;
					} catch (Exception e) {
						listen.log(e.getMessage(),DownloadPanel.ERROR);
					}
				}
			}
		} else {
			status = COMPLETE;
			//listen.downFile();//Darke
		}
		latch.countDown();
	}
	
	public void downloadSmb() {
		if (true) {
			String name=getFileName(url);
			String url_ =listen.getFileUrl(name);
			url_=url_.substring(0,url_.lastIndexOf(name)).replace("/", "\\");
			try {
				copyfile(smbfile.getCanonicalPath().replace("/", "\\"),url_);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			/*RandomAccessFile file = null;//Darke
//			BufferedOutputStream outm=null;
			FileInputStream stream = null;
			try {

				//connection.setRequestProperty("Range", "bytes=" + downloaded + "-");//Darke
//				connection.setConnectTimeout(100000);
//				smbfile.setRequestProperty("Range", "bytes=" + startposition + "-"+endposition);//Darke
//				smbfile.connect();
				//contentLength = connection.getContentLength();
				int tcontentLength =  (int) (endposition-startposition);
				//if (contentLength < 1) {//Darke
				if (tcontentLength < 1) {//Darke
					error();
					listen.log("获取数据长度错误！",DownloadPanel.ERROR+"DownLoad File connection--");
				}
				if (size == -1) {
					//size = contentLength;//Darke
					size=tcontentLength;//Darke
				}
				downloaded=0;
				--------------------B (Darke 2012.01.31)--------------------
				//String url_ = getFileName(url).startsWith("Pastoral") ? getFileName(url) : "lib\\" + getFileName(url);
				String name=getFileName(url);
				try {
					stream = new FileInputStream(smbfile);
					stream.skip(startposition);
				}catch(Exception k){
					listen.log(k.getMessage(),DownloadPanel.ERROR+"DownLoad File connection--");
					DownloadPanel downloadp=(DownloadPanel) listen;
					boolean ismain=name.equalsIgnoreCase(downloadp.mainFile);
					if(downloadp.errorMessage.isEmpty()){
						downloadp.errorMessage=((k instanceof java.io.FileNotFoundException)?
								"服务器无法找到"+(ismain?"运行文件":"文件")+"："+name:k.getMessage());
					}
					
					throw k;
				}

				String url_ =listen.getFileUrl(name)+"_"+version+"_"+num;
				System.out.println("DownUrl:"+url_);
				//file = new RandomAccessFile(DownloadPanel.u + url_, "rw");
				file = new RandomAccessFile(url_, "rw");//Darke
//				outm=new BufferedOutputStream(new FileOutputStream(url_, true));
				--------------------E (Darke 2012.01.31)--------------------
				file.seek(file.length());//Darke
				////stream = connection.getInputStream();
				while (status == DOWNLOADING) {
					// System.out.println("Download...");
					byte buffer[];
					if (size - downloaded > MAX_BUFFER_SIZE) {
						buffer = new byte[MAX_BUFFER_SIZE];
					} else {
						buffer = new byte[(int) (size - downloaded)];
					}
					try{
						int read = stream.read(buffer);
						if (read == -1) {
							break;
						}
						file.write(buffer, 0, read);
	//					outm.write(buffer, 0, read);//Darke
						downloaded += read;
						if(downloaded%5000==0){
							outm.flush();
						}
						listen.updateScreen(read);
						if(downloaded>=size){
							status = COMPLETE;
						}
					}catch(Exception k){
						k.printStackTrace();
						counterror++;
						if(counterror>60){
							DownloadPanel downloadp=(DownloadPanel) listen;
							downloadp.errorMessage="网络状况不正常！请重新下载！";
							beclose=true;
							throw k;
						}
						try{
							stream.close();
						}catch(Exception l){
						}
						//connection.setRequestProperty("Range", "bytes=" + downloaded + "-");//Darke
//						connection.setConnectTimeout(100000);
						//contentLength = connection.getContentLength();
						tcontentLength = (int) (endposition-startposition-downloaded);
						//if (contentLength < 1) {//Darke
						if (tcontentLength < 1) {//Darke
							error();
							listen.log("获取数据长度错误！",DownloadPanel.ERROR+"DownLoad File connection--");
						}
						if (size == -1) {
							//size = contentLength;//Darke
							size=tcontentLength;//Darke
						}
						try {
							stream = new FileInputStream(smbfile);
							stream.skip(startposition+downloaded);
						}catch(Exception m){
							listen.log(k.getMessage(),DownloadPanel.ERROR+"DownLoad File connection--");
							DownloadPanel downloadp=(DownloadPanel) listen;
							boolean ismain=name.equalsIgnoreCase(downloadp.mainFile);
							if(downloadp.errorMessage.isEmpty()){
								downloadp.errorMessage=((k instanceof java.io.FileNotFoundException)?
										"服务器无法找到"+(ismain?"运行文件":"文件")+"："+name:k.getMessage());
								throw m;
							}
						}
					}
				}
				try {
					file.close();
					--------------------B (Darke 2012.03.02)--------------------
					outm.flush();
					outm.close();
					outm = null;
					--------------------E (Darke 2012.03.02)--------------------
					stream.close();
					stream = null;
				} catch (Exception e) {
					listen.log(e.getMessage(),DownloadPanel.ERROR+"DownLoad Close IOStream--");
					e.printStackTrace();
				}

				// if (status == DOWNLOADING) {
				// status = COMPLETE;
				// System.out.println("call");
				// listen.call();
				// }
				// listen.runEXE();
				//listen.downFile();

			} catch (Exception e) {
				listen.log(e.getMessage(),DownloadPanel.ERROR+"DownLoad--");
				e.printStackTrace();
				//error();
			} finally {
				//listen.downFile();//Darke
				if (outm != null) {//Darke
					try {
						outm.flush();
						outm.close();
						outm = null;
					} catch (Exception e) {
					}
				}
				if (stream != null) {
					try {
						file.close();
						stream.close();
						stream = null;
					} catch (Exception e) {
						listen.log(e.getMessage(),DownloadPanel.ERROR+"Finally DownLoad Close IOStream--");
					}
				}
			}*/
		} else {
			status = COMPLETE;
			//listen.downFile();//Darke
		}
		latch.countDown();
	}
	
	public void run() {
		if (true) {
			/*--------------------B (Darke 2012.03.02)--------------------*/
			if(startposition>=endposition){
				latch.countDown();
				return;
			}
			if(isLAN){
				downloadSmb();
				return;
			}
			/*--------------------E (Darke 2012.03.02)--------------------*/
			// System.out.println(url);
			RandomAccessFile file = null;//Darke
//			BufferedOutputStream outm=null;
			InputStream stream = null;
			try {
				HttpURLConnection connection = (HttpURLConnection) url.openConnection();
				System.out.println("链接端口号：：--------"+url.getPort());
				//connection.setRequestProperty("Range", "bytes=" + downloaded + "-");//Darke
//				connection.setConnectTimeout(100000);
				connection.setRequestProperty("Range", "bytes=" + startposition + "-"+endposition);//Darke
				connection.connect();
				if (connection.getResponseCode() / 100 != 2) {
					error();
					listen.log("不是有效的 HTTP",DownloadPanel.ERROR+"DownLoad File connection--");
				}
				//contentLength = connection.getContentLength();
				int tcontentLength = connection.getContentLength();
				//if (contentLength < 1) {//Darke
				if (tcontentLength < 1) {//Darke
					error();
					listen.log("获取数据长度错误！",DownloadPanel.ERROR+"DownLoad File connection--");
				}
				if (size == -1) {
					//size = contentLength;//Darke
					size=tcontentLength;//Darke
				}
				downloaded=0;
				/*--------------------B (Darke 2012.01.31)--------------------*/
				//String url_ = getFileName(url).startsWith("Pastoral") ? getFileName(url) : "lib\\" + getFileName(url);
				String name=getFileName(url);
				try {
					stream = connection.getInputStream();
				}catch(Exception k){
					listen.log(k.getMessage(),DownloadPanel.ERROR+"DownLoad File connection--");
					DownloadPanel downloadp=(DownloadPanel) listen;
					boolean ismain=name.equalsIgnoreCase(downloadp.mainFile);
					if(downloadp.errorMessage.isEmpty()){
						downloadp.errorMessage=((k instanceof java.io.FileNotFoundException)?
								"服务器无法找到"+(ismain?"运行文件":"文件")+"："+name:k.getMessage());
					}
					
					throw k;
				}

				String url_ =listen.getFileUrl(name)+"_"+version+"_"+num;
				System.out.println("DownUrl:"+url_);
				//file = new RandomAccessFile(DownloadPanel.u + url_, "rw");
				file = new RandomAccessFile(url_, "rw");//Darke
//				outm=new BufferedOutputStream(new FileOutputStream(url_, true));
				/*--------------------E (Darke 2012.01.31)--------------------*/
				file.seek(file.length());//Darke
				////stream = connection.getInputStream();
				while (status == DOWNLOADING) {
					// System.out.println("Download...");
					byte buffer[];
					if (size - downloaded > MAX_BUFFER_SIZE) {
						buffer = new byte[MAX_BUFFER_SIZE];
					} else {
						buffer = new byte[(int) (size - downloaded)];
					}
					try{
						int read = stream.read(buffer);
						if (read == -1) {
							break;
						}
						file.write(buffer, 0, read);
	//					outm.write(buffer, 0, read);//Darke
						downloaded += read;
						/*if(downloaded%5000==0){
							outm.flush();
						}*/
						listen.updateScreen(read);
					}catch(Exception k){
						k.printStackTrace();
						counterror++;
						if(counterror>60){
							DownloadPanel downloadp=(DownloadPanel) listen;
							downloadp.errorMessage="网络状况不正常！请重新下载！";
							beclose=true;
							throw k;
						}
						try{
							stream.close();
							connection.disconnect();
						}catch(Exception l){
						}
						connection = (HttpURLConnection) url.openConnection();
						//connection.setRequestProperty("Range", "bytes=" + downloaded + "-");//Darke
//						connection.setConnectTimeout(100000);
						connection.setRequestProperty("Range", "bytes=" + (startposition +downloaded)+ "-"+endposition);//Darke
						connection.connect();
						if (connection.getResponseCode() / 100 != 2) {
							error();
							listen.log("不是有效的 HTTP",DownloadPanel.ERROR+"DownLoad File connection--");
						}
						//contentLength = connection.getContentLength();
						tcontentLength = connection.getContentLength();
						//if (contentLength < 1) {//Darke
						if (tcontentLength < 1) {//Darke
							error();
							listen.log("获取数据长度错误！",DownloadPanel.ERROR+"DownLoad File connection--");
						}
						if (size == -1) {
							//size = contentLength;//Darke
							size=tcontentLength;//Darke
						}
						downloaded=0;
						try {
							stream = connection.getInputStream();
						}catch(Exception m){
							listen.log(k.getMessage(),DownloadPanel.ERROR+"DownLoad File connection--");
							DownloadPanel downloadp=(DownloadPanel) listen;
							boolean ismain=name.equalsIgnoreCase(downloadp.mainFile);
							if(downloadp.errorMessage.isEmpty()){
								downloadp.errorMessage=((k instanceof java.io.FileNotFoundException)?
										"服务器无法找到"+(ismain?"运行文件":"文件")+"："+name:k.getMessage());
								throw m;
							}
						}
					}
				}

				try {
					file.close();
					/*--------------------B (Darke 2012.03.02)--------------------*/
					/*outm.flush();
					outm.close();
					outm = null;*/
					/*--------------------E (Darke 2012.03.02)--------------------*/
					stream.close();
					stream = null;
				} catch (Exception e) {
					listen.log(e.getMessage(),DownloadPanel.ERROR+"DownLoad Close IOStream--");
					e.printStackTrace();
				}

				// if (status == DOWNLOADING) {
				// status = COMPLETE;
				// System.out.println("call");
				// listen.call();
				// }
				// listen.runEXE();
				//listen.downFile();

			} catch (Exception e) {
				listen.log(e.getMessage(),DownloadPanel.ERROR+"DownLoad--");
				e.printStackTrace();
				//error();
			} finally {
				//listen.downFile();//Darke
				/*if (outm != null) {//Darke
					try {
						outm.flush();
						outm.close();
						outm = null;
					} catch (Exception e) {
					}
				}*/
				if (stream != null) {
					try {
						file.close();
						stream.close();
						stream = null;
					} catch (Exception e) {
						listen.log(e.getMessage(),DownloadPanel.ERROR+"Finally DownLoad Close IOStream--");
					}
				}
			}
		} else {
			status = COMPLETE;
			//listen.downFile();//Darke
		}
		latch.countDown();
	}

	/**
	 * 绘制下载进度
	 * 
	 */
	public synchronized void draw(long downded) {
		DownloadPanel downpanel = (DownloadPanel) listen;
		int progress = getproce(downded);//getProgress();
		String mes = (getDownloadName() + "-已完成进度 " + progress + " %").intern();
		downpanel.progressBar.setString(mes);
		downpanel.progressBar.setValue(progress);
		if (progress == 100) {
			status = COMPLETE;
			// // 隐藏进度条
			// // downpanel.progressBar.setVisible(false);
			// // downpanel.validate();
		}
	}

}

